<template>
  <div>
    <div v-if="isShowEchartsDome" style="height:calc(88vh - 120px);width: 99%;padding:0">
        <RelationGraph ref="seeksRelationGraph"
                       :options="userGraphOptions"
                       :on-node-click="onNodeClick"
                       :on-line-click="onLineClick" />
    </div>
     <div class="echarts-dome-class">
         <el-button v-if="!isShowEchartsDome" @click="showpup"  class="el-icon-circle-plus">添加关联关系</el-button>
     </div>
  </div>
</template>
 <script>
 import {QUERYELEVANCEVIEW, assoViewMaintain} from '@api/url'
 import RelationGraph from 'relation-graph'
 export default {
   name: 'Demo',
   components: { RelationGraph },
   data () {
     return {
         LineHeight: 30, // 行高度
         isShowEchartsDome: true,
         lineWidth: 120, // 行宽度
         userGraphOptions: {
            'backgrounImage': '',
            'backgrounImageNoRepeat': true,

            lineShape: 4,
            'layouts': [
              {
                'label': '中心',
                padding: 0,
                'layoutName': 'center',
                'defaultNodeShape': 1, // 默认形状 默认的节点形状，0:圆形；1:矩形
                'defaultLineShape': 4, // 默认的线条样式（1:直线/2:样式2/3:样式3/4:折线/5:样式5/6:样式6）使用示例
                'from': 'right'
              }
            ],
            padding: 0,
            'defaultNodeBorderWidth': 0, // 默认的节点边框粗细（像素）
            defaultNodeWidth: 180,
            disableDrag: true, // 是否禁用节点的拖动功能
            'defaultNodeShape': 1, // 默认形状 默认的节点形状，0:圆形；1:矩形
            'allowShowMiniNameFilter': true,
            'allowShowMiniToolBar': true,
             defaultNodeColor: 'white', // 节点背景色
             color:'red',
            'defaultLineShape': 4// 线条样式（1:直线/2:样式2/3:样式3/4:折线/5:样式5/6:样式6
      },
      //  主表
       main: [{
          maintableName: '', // 主表名称
          mainTemplate: '', // 主表的字符串模板
          id: '', // id
          relationType: ''// 关联类型
       }],
      //  关联表
       relevence: []
     }
   },
    watch: {
    menuData (val) {
      console.log(val, '选中的数据为----------------------')
      // this.isShowEchartsDome=false
       this.queryElevanceViews(val)
    }
  },
  props: {
    menuData: null
  },

   mounted () {
     this.queryElevanceViews()
   },
   methods: {
     // 关闭当前页面
    closeBox () {
      this.$emit('closePage')
    },
    showpup () {
      this.$emit('closePage', 'showpup')
    },
    // 查询关联视图
    queryElevanceViews () {
      let param = {
        'modelId': this.$storeSave.state.selectMenuData.menuId
      }

      //  关联表
      this.relevence = []
      this.main = [{maintableName: '', // 主表名称
                mainTemplate: '', // 主表的字符串模板
                id: ''}],
      this.isShowEchartsDome = true
      this.$http.post(QUERYELEVANCEVIEW, param).then(res => {
        console.log('selectDemo查询关联视图信息成功')
        console.log(res)
        this.content = {}
          if (res.data.code == '200' && res.data.data.length > 0) {
              let mainObjId = ''// 存主表id
              let slaveobjSlaveTableName = ''// 辅表名
              let slaveobjSlaveTemplate = ''// 附表字段模板
              let slaveobjId = ''// 辅表id

              // let slaveobjHeight=""//辅表高度
            res.data.data.forEach((item, index) => {
              let relationTypelabel = this.getLabel(item.relationType)
              this.height = 0
              let mainFontArray = []
               let mainTemplate = `<div style="text-align:center;border:1px solid #ccc;margin:0;border-radius:4px;bo">`
               let slaveFontArray = []
              let slaveTemplate = ''
              item.lists.forEach((ele, ind) => {
              ele.relationId = item.relationId
              ele.modelId = item.modelId
              ele.slaveId = item.slaveId
              ele.relationType = item.relationType
              ele.relationTypelabel = this.getLabel(item.relationType)
              ele.masterTableName = item.masterTableName
              ele.slaveTableName = item.slaveTableName
              if (index == 0 && ind == 0) {
                // 主表名称
                mainTemplate += `<p style="background:#17a2b8;line-height:${this.LineHeight}px">${item.masterTableName}</p>`
              }
                mainObjId = ele.relationId
              // 关联表信息
              if (ind == 0) {
                // 加表名
                slaveobjSlaveTemplate = `
                <div style="text-align:center;border:1px solid #ccc;color:black;margin:0;border-radius:4px">

                  <p style="background:#17a2b8;color:#fff;margin:0;line-height:${this.LineHeight}px">
                    ${item.slaveTableName}
                  </p>
                  <div style="display:flex; border-radius:4px"><div style="margin: auto; border-radius:4px"><a style="color:#17a2b8">修改</a></div>
                <div>`
              }
              slaveobjSlaveTableName = item.slaveTableName
              slaveobjId = `slaveId${ele.relationId}`
              slaveTemplate += `<p style="margin:0;line-height:${this.LineHeight}px;width:${this.lineWidth}px;">${ele.slaveShowfld}</p>`
              mainFontArray.push(ele.masterShowfld)
              slaveFontArray.push(ele.slaveShowfld)
              mainTemplate += `<p style="color:black;margin:0;line-height:${this.LineHeight}px;width:${this.lineWidth + 60}px;">${ele.masterShowfld}</p>`
            })
            slaveTemplate += `</div></div></div>`
            slaveobjSlaveTemplate += slaveTemplate
            mainTemplate += `</div>`
            if (index != 0) {
              this.main.push({
                // height:this.height,//决定主表高度
                mainTemplate: mainTemplate, // 主表一组数据下边框
                id: mainObjId,
                mainFontArray: mainFontArray, // 主表关联字段
                relationType: relationTypelabel// 关联类型
              })
           } else {
             this.main[0].mainTemplate = mainTemplate
             this.main[0].id = mainObjId
             this.main[0].mainFontArray = mainFontArray
             this.main[0].relationType = relationTypelabel// 关联类型
           }
            this.relevence.push({
              id: slaveobjId,
              slaveTableName: slaveobjSlaveTableName,
              slaveTemplate: slaveobjSlaveTemplate,
              slaveFontArray: slaveFontArray
            })
          })
          this.content = res.data.data
          console.log(this.main)
          console.log('____++++++++++^^^^^^^^^^^^^^^^^^^^^')
          console.log(this.relevence)
          this.showSeeksGraph()
          } else if (res.data.code == '200' && res.data.data.length < 1) {
            this.isShowEchartsDome = false
          }
      }).catch(err => {
        this.content = {}
        this.isShowEchartsDome = false
        console.log('查询关联视图信息失败')
        console.log(err)
      })
    },
    // 将关联类型key值进行转换
    getLabel (relationType) {
      let arr = [{value: 1, label: '1:1'}, {value: 2, label: '1:N'}, {value: 3, label: 'N:1'}, {value: 4, label: 'N:N'}]
      let label = ''
      arr.forEach(ele => {
        if (relationType == ele.value) {
          label = ele.label
        }
      })
      return label
    },

    // 修改
    modify (data) {
      // 主表id  modelId
      // 附表id ：slaveId
      // 关联id：relationId
      this.$emit('tagisShowpup', data, {modelId: this.menuData.menuId, slaveId: this.menuData.slaveId})
    },
    // 删除
    deleteData (data) {
      let param = {
         optMode: 'D',
          relationId: data.relationId, // 关联id
          modelId: data.modelId,
          slaveId: data.slaveId // 从表id
      }
      this.$http.post(assoViewMaintain, param).then(res => {
        console.log(res)
        if (res.data.code == '200') {
          this.$confirm('删除成功', '提示', {
            confirmButtonText: '确定',
            type: 'success'
          })
          this.queryElevanceViews()
        } else {
          this.$confirm(res.data.message, '提示', {
            confirmButtonText: '确定',
            type: 'fail'
          })
        }
      }).catch(err => {
        console.log(err)
        this.$confirm('删除失败', '提示', {
            confirmButtonText: '确定',
            type: 'fail'
          })
      })
    },
     showSeeksGraph (query) {
        debugger
       // 以上数据中的node和link可以参考"Node节点"和"Link关系"中的参数进行配置
       let __graph_json_data = {
         rootId: this.main[0].id,
         nodes: [],
         links: []
       }
       let Y = 0
       this.main.forEach((ele, index) => {
         let leftRX = 10// 辅表字段X轴
         let RighrX = 610
         let mainY = 0
         if (index == 0) {
           __graph_json_data.nodes.push({ id: ele.id, text: ele.mainTemplate, fixed: true, x: 300, y: mainY, disableDrag: true}) // 主表)  ,height:(ele.mainFontArray.length+1)*this.LineHeight
         } else if (index == 1) {
           Y += mainY + this.LineHeight + 14 + ((this.main[index - 1].mainFontArray.length) * this.LineHeight) // (this.main[index-1].mainFontArray.length+1)*this.LineHeight+mainY+15
            __graph_json_data.nodes.push({ id: ele.id, text: ele.mainTemplate, fixed: true, x: 300, y: Y, disableDrag: true}) // 主表)  ,height:(ele.mainFontArray.length+1)*this.LineHeight
         } else {
           Y += (this.main[index - 1].mainFontArray.length) * this.LineHeight
          __graph_json_data.nodes.push({ id: ele.id, text: ele.mainTemplate, fixed: true, x: 300, y: Y, disableDrag: true})
         }
         this.relevence.forEach((Element, ind) => {
             if (ind == 0) {
                __graph_json_data.nodes.push({ id: Element.id, text: Element.slaveTemplate, fixed: true, x: RighrX, y: mainY + 40, disableDrag: true, padding: 'none'}) // height:(Element.slaveFontArray.length)*this.LineHeight,
            } else if (ind == 1) {
              __graph_json_data.nodes.push({ id: Element.id, text: Element.slaveTemplate, fixed: true, x: leftRX, y: (this.main[0].mainFontArray.length + 1) * this.LineHeight + mainY + 10, disableDrag: true, padding: 'none'})// height:(Element.slaveFontArray.length+1)*this.LineHeight+20,
            } else if (ind % 2 == 0 && index > 1) {
              // 右边

              console.log(index)
              __graph_json_data.nodes.push({ id: Element.id, text: Element.slaveTemplate, fixed: true, x: RighrX, y: Y + 60, padding: 'none'})
            } else if (ind % 2 == 1 && index > 2) {
              // 左边
              __graph_json_data.nodes.push({ id: Element.id, text: Element.slaveTemplate, fixed: true, x: leftRX, y: Y + 60, padding: 'none'})
            }
           })
         // __graph_json_data.links.push({ from: this.main[index].id, to: this.relevence[index].id, text:this.main[index].relationType, color: '#43a2f1' })
         __graph_json_data.links.push({ from: this.main[index].id, to: this.relevence[index].id, text: `${this.main[index].relationType}   删除`, color: '#43a2f1' })
       })
       this.$refs.seeksRelationGraph.setJsonData(__graph_json_data, (seeksRGGraph) => {
         // Called when the relation-graph is completed
         console.log(seeksRGGraph, '---------------99999999999999999999999999')
       })
     },
     onNodeClick (nodeObject, $event) {
       console.log('onNodeClick:', nodeObject)
       console.log(nodeObject.text)
       console.log(nodeObject.id)
       // 点击了辅表，编辑
       if (nodeObject.id.indexOf('slaveId') != -1) {
         let relationId = nodeObject.id.substr(7)
         console.log(relationId)
           let selectObj
          this.content.forEach(ele => {
            console.log(ele)
            if (ele.relationId == relationId) {
              selectObj = ele.lists
            }
            // ele.lists.find(item=>{
            //   if(item.relationId == relationId){
            //     selectObj = item
            //     return
            //   }
            // })
          })
         this.modify(selectObj)
       }
     },
     // 删除，点击线条
     onLineClick (lineObject, $event) {
        let selectObj
      this.content.forEach(ele => {
        ele.lists.find(item => {
          if (item.relationId == lineObject.fromNode.id) {
            selectObj = item
          }
       })
      })
      this.$confirm('此操作删除该记录, 是否继续?', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true
      }).then(() => {
        this.deleteData(selectObj)
      }).catch(action => {
        console.log('取消')
      })
      }
   }
 }
 </script>
<style lang='less' scoped>

.echarts-dome-class {
    width: auto;
    height: auto;
    margin-top: 10%;
    text-align: center;
}
</style>
